<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        #box {
            width: 100px;
            height: 100px;
            background-color: pink;
            border-radius: 100%;
            position: absolute;
        }
    </style>
</head>

<body>
    <div id="box">

    </div>
    <script>
        var box = document.querySelector('#box')
        //获取页面元素
        box.onmousedown = function (e) {
            //设置一个鼠标点击函数
            //兼容语句
            e = e || window.event
            //用一个变量来接收浏览器可视窗口的X，Y值

            var disX = e.offsetX, disY = e.offsetY
            console.log(disX, disY)
            //给document设置一个鼠标指针事件函数
            document.onmousemove = function (e) {
                e = e || window.event
                var left = e.clientX - disX
                var top = e.clientY - disY
                if (left < 0) left = 0
                if (top < 0) top = 0
                if (left > window.innerWidth - box.offsetWidth) {
                    left = window.innerWidth - box.offsetWidth
                }
                if (top > window.innerHeight - box.offsetHeight) {
                    top = window.innerHeight - box.offsetHeight
                }
                box.style.left = left + 'px'
                box.style.top = top + 'px'
            }
            document.onmouseup = function () {
                document.onmousemove = null
            }
        }

    </script>
</body>

</html>